import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import Login from '@/views/Login.vue'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css' // 进度条样式

const rootRoutes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: {
      title: '系统登录'
    }
  },
  {
    path: '/login/next',
    name: 'login_next',
    component: () => import('@/views/LoginNext.vue'),
    meta: {
      title: '系统登录'
    }
  },
  {
    path: '/login/pwd',
    name: 'pwdlogin',
    component: () => import('../views/LoginPwd.vue'),
    meta: {
      title: '账号密码登录'
    }
  },
  {
    path: '/home',
    name: 'TheRoot',
    redirect: '/show',
    component: () => import('../views/TheRoot.vue'),
    children: [
      {
        path: '/show',
        name: 'show',
        component: () => import('../views/Show.vue'),
        meta: {
          title: '首页'
        }
      },
      {
        path: '/page',
        name: 'page',
        component: () => import('../views/Page.vue'),
        meta: {
          title: '家教单'
        }
      },
      {
        path: '/myInfo',
        name: 'myInfo',
        component: () => import('../views/MyInfo.vue'),
        meta: {
          title: '我的信息'
        }
      }
      , {
        path: '/message',
        name: 'message',
        component: () => import('../views/Message.vue'),
        meta: {
          title: '消息中心'
        }
      }, {
        path: '/aiChat',
        name: 'order',
        component: () => import('../views/AiChat.vue'),
        meta: {
          title: 'ai聊天'
        }
      }
    ]
  },
  {
    path: '/403',
    meta: {
      title: '403 Forbidden',
      noAuth: true
    },
    component: () => import('../views/403.vue')
  },
  {
    path: '/404',
    meta: {
      title: '404 NotFound',
      noAuth: true
    },
    component: () => import('../views/404.vue')
  },
  {
    path: '/:path(.*)',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: rootRoutes
})

// 全局路由守卫 前置守卫
// 白名单 只要在白名单里就放行
const whitePath = ['/login', '/login/next', '/login/pwd']
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (to && to.meta && to.meta.title) {
    document.title = to.meta.title;
  }
  // 判断是否登录
  if (!whitePath.includes(to.path)) {
    // 判断本地有无用户数据
    if (!localStorage.getItem('userInfo')) {
      router.push('/login')
      return;
    }
    next();
    return;
  }
  next();
})
router.afterEach(() => {
  NProgress.done()
})

export default router
